/* eslint-disable no-console */
import React, { Component } from 'react';
import WPT from 'wpt';

import { encrypt, getParams } from '../Tool.js';

import { Button, Confirm, Header, Items, Text, Tip } from './content.js';

import './index.less';

import { home } from '@/api';
import showHide from '@wpt/showHide';

@showHide
export default class Home extends Component {
    static pageConfig = { fixedIcon: { backHome: false } };

    constructor(props) {
        super(props);
        this.state = {
            showTip: false,
            tipInfo: '',
            showConfirm: false,
            confirmInfo: '',
            confirmCallback: null,
            confirmMsg: null,
            long_time: '',
            subject_name: ''
        };
        this.nameRex = /^[\u4e00-\u9fa5]{2,4}$/;
        this.phoneRex = /^1[3|4|5|7|8][0-9]{9}$/;
        this.data = [
            '1、本考试系统及内容仅供微拍堂学员进行在线考评系统使用为学员提供适当的产品和服务时，微拍堂将履行保密服务。',
            '2、本场考试时间为_分钟，用户可通过点击下一题进行切换操作，请学员根据时间合理安排时间进行解答，' +
            '超过考试时间系统将自动进行提交，提前完成作答可以点击考试完成进行提交，一旦提交视为考试结束，无法再进行作答。',
            '3、填写手机号，姓名以及选择考试科目，点击_按钮视为本次考试正式开始。',
            '4、本考试全程需打开电脑摄像功能进行随机截屏管理，点击开始考试视为同意授权本次操作，' +
            '考试过程中切勿关闭考试页面和摄像功能，关闭视为本次考试结束。'
        ];

        this.getUserMedia = (constraints, success, error) => {
            if (navigator.mediaDevices.getUserMedia) {
                //最新的标准API
                navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
            } else if (navigator.webkitGetUserMedia) {
                //webkit核心浏览器
                navigator.webkitGetUserMedia(constraints, success, error)
            } else if (navigator.mozGetUserMedia) {
                //firfox浏览器
                navigator.mozGetUserMedia(constraints, success, error);
            } else if (navigator.getUserMedia) {
                //旧版API
                navigator.getUserMedia(constraints, success, error);
            }
        }
    }

    componentDidMount() {
        WPT.setTitle('移动端');

        this.getData();
    }

    getData = () => {
        const params = getParams();
        if (params === null || params.subject_id === undefined) {
            this.setTip('没有找到试卷编号', () => WPT.showPage('/e403'));
            return;
        }

        // window.sessionStorage.setItem('testInfo', JSON.stringify({
        //     long_time: 1,
        //     subject_name: '张旭真不是个东西'
        // }));
        // this.setState({
        //     long_time: 1,
        //     subject_name: '张旭真不是个东西'
        // });

        //window.sessionStorage.setItem('subject_id', params['subject_id']);
        window.subject_id = params['subject_id'];
        home.getExamInfo({
            subject_id: params['subject_id']
        }).then((data) => {
            const start = data.start;
            const end = data.end;
            // eslint-disable-next-line prefer-destructuring
            this.start_hour = start.split(' ')[1];
            this.start_time = Date.parse(new Date(start.replaceAll(' ', ' ')));
            this.end_time = Date.parse(new Date(end.replaceAll(' ', ' ')));
            // window.sessionStorage.setItem('testInfo', JSON.stringify({
            //     long_time: data.long_time,
            //     subject_name: data.subject_name,
            // }));
            this.setState({
                long_time: data.long_time,
                subject_name: data.subject_name
            });
        }).catch(() => {
            this.setTip('获取试卷失败');
        });
    }

    setTip = (info, cb) => {
        this.setState({
            showTip: true,
            tipInfo: info
        }, () => setTimeout(() =>
            this.setState({
                showTip: false,
                tipInfo: ''
            }, () => {
                cb && cb();
            }), 1500));
    }

    setConfirm = (info, msg, callBack) => {
        this.setState({
            showConfirm: true,
            confirmInfo: info,
            confirmMsg: msg,
            confirmCallback: callBack
        })
    }

    prove = () => {
        let { name, phone } = this.inputsRef.data;
        name = name.trim();
        phone = phone.trim();
        if (!this.nameRex.test(name)) {
            this.setTip('姓名只能为2至4位的中文汉字');
            return;
        }
        if (!this.phoneRex.test(phone)) {
            this.setTip('非法手机号');
            return;
        }
        const now = Date.now();
        if (now < this.start_time) {
            this.setTip('考试暂未开始，请' + this.start_hour.slice(0, this.start_hour.length - 3) + '与准时参加');
            return;
        }
        if (now > this.end_time) {
            this.setTip('本场考试已结束')
            return;
        }

        if (window.stu_id !== undefined) {
            this.setTip('你不能再参加本场考试');
            return;
        }

        home.addStudent({
            stu_name: name,
            phone: window.btoa(phone),
            subject_id: window.subject_id
        }).then((data) => {
            // eslint-disable-next-line no-console
            if (window.stu_id === undefined) {
                this.setConfirm(
                    ['取消', '确定'],
                    '是否准备好考试，一旦开始中途中断或者关闭则示为考试结束？',
                    [
                        () => this.setState({ showConfirm: false }),
                        () => {
                            this.setState({ showConfirm: false })
                            //window.sessionStorage.setItem('stu_id', data.stu_id);
                            window.stu_id = data.stu_id;
                            WPT.showPage('/main' + '?' + 'stu_id='
                                + data.stu_id + '&subject_id='
                                + window.subject_id + '&long_time='
                                + this.state.long_time + '&subject_name='
                                + this.state.subject_name);
                        }
                    ]);
            } else {
                this.setTip('你不能再参加本场考试');
            }
        }).catch(() => {
            this.setTip('网络错误')
        });

        // eslint-disable-next-line no-constant-condition
        {
            // if (true || navigator.mediaDevices.getUserMedia || navigator.getUserMedia ||
            //     navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
            //     this.getUserMedia({ video: { width: 480, height: 320 } },
            //         s => {
            //             console.log('媒体正常' + s);
            //             home.addStudent({
            //                 name: name,
            //                 phone: window.btoa(phone)
            //             }).then((data) => {
            //                 // eslint-disable-next-line no-console
            //                 if (window.stu_id === undefined) {
            //                     this.setConfirm(
            //                         ['取消', '确定'],
            //                         '是否准备好考试，一旦开始中途中断或者关闭则示为考试结束？',
            //                         [
            //                             () => this.setState({ showConfirm: false }),
            //                             () => {
            //                                 this.setState({ showConfirm: false })
            //                                 window.stu_id = data.stu_id;
            //                                 WPT.showPage('/main');
            //                             }
            //                         ]);
            //                 } else {
            //                     this.setTip('你不能再参加本场考试');
            //                 }
            //             }).catch((e) => {
            //                 console.log(e);
            //             });
            //         },
            //         e => {
            //             console.log(`访问用户媒体设备失败${e.name}, ${e.message}`);
            //             this.setConfirm(['取消', '确定'], '摄像头有异常，请检查设备后再考试', [
            //                 () => this.setState({ showConfirm: false }),
            //                 () => this.setState({ showConfirm: false })
            //             ]);
            //         });
            // }
        }
    }

    render() {
        return (
            <div
                className="page-index-wrapper"
                ref={(c) => {
                    this.$root = c;
                }}
            >
                <Header></Header>
                <div className="page-index-content-box">
                    <div className="page-index-content-box-inner">
                        <Text list={this.data} time={this.state.long_time}></Text>
                        <Items onRef={(ref) => { this.inputsRef = ref }} subjectName={this.state.subject_name}></Items>
                        <Button jump={this.prove}></Button>
                    </div>
                    {
                        this.state.showTip
                            ?
                            <Tip
                                info={this.state.tipInfo}
                            ></Tip> : null
                    }
                </div>
                {
                    this.state.showConfirm
                        ?
                        <Confirm
                            info={this.state.confirmInfo}
                            callBack={this.state.confirmCallback}
                            msg={this.state.confirmMsg}
                        ></Confirm> : null}
            </div>
        );
    }
}